import React, { useEffect, useState } from 'react';
import axios from 'axios';
// import { message } from 'antd'; 
import { useParams, useNavigate } from 'react-router-dom';
import {
  Form,
  Input,
  InputNumber,
  Button,
  Card,
  Typography,
  Spin,
  Alert,
  Upload,
  message,
} from 'antd';
import type { UploadFile } from 'antd/es/upload/interface';
import { UploadOutlined } from '@ant-design/icons';

const { Title } = Typography;
const { TextArea } = Input;

type Prize = {
  prize_image: string;
  prize_name: string;
  prize_description: string;
  points: number;
  stock: number;
};

const EditPrize: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  const [formData, setFormData] = useState<Prize>({
    prize_image: '',
    prize_name: '',
    prize_description: '',
    points: 0,
    stock: 0,
  });

  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string>('');
  const [uploading, setUploading] = useState<boolean>(false);

  // 使用UploadFile类型，控制上传文件列表
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  useEffect(() => {
    const fetchPrize = async () => {
      try {
        const response = await axios.get<Prize>(
          `http://localhost:5000/api/searchPrize/${id}`
        );
        setFormData(response.data);

        if (response.data.prize_image) {
          setFileList([
            {
              uid: '-1',
              name: '当前图片',
              status: 'done',
              url: `http://localhost:5000${response.data.prize_image}`,
            },
          ]);
        } else {
          setFileList([]);
        }
      } catch (err) {
        setError('加载奖品失败');
      } finally {
        setLoading(false);
      }
    };

    fetchPrize();
  }, [id]);

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: name === 'points' || name === 'stock' ? Number(value) : value,
    }));
  };

  const handleNumberChange = (value: number | null, name: keyof Prize) => {
    if (value !== null) {
      setFormData((prev) => ({ ...prev, [name]: value }));
    }
  };

  // 上传文件改变事件
  const handleUploadChange = (info: {
    file: UploadFile;
    fileList: UploadFile[];
  }) => {
    let newFileList = [...info.fileList];
    newFileList = newFileList.slice(-1); // 保留一个文件
    setFileList(newFileList);

    if (info.file.status === 'uploading') {
      setUploading(true);
    } else if (info.file.status === 'done') {
      setUploading(false);
      const res = info.file.response as { url?: string };
      if (res && res.url) {
  setFormData(prev => ({ ...prev, prize_image: res.url! })); // 这里加 ! 告诉TS不会是undefined
  message.success(`${info.file.name} 上传成功`);
} else {
  message.error('上传失败，服务器未返回图片地址');
}

    } else if (info.file.status === 'error') {
      setUploading(false);
      message.error(`${info.file.name} 上传失败`);
    }
  };

  // 删除上传图片时，清空 prize_image 字段
  const handleRemove = () => {
    setFormData((prev) => ({ ...prev, prize_image: '' }));
    setFileList([]);
  };

const handleSubmit = async () => {
  try {
    const res = await axios.put(`http://localhost:5000/api/matchPrize/${id}`, formData);
    console.log('更新结果：', res.data); // ✅ 打印结果以确认执行成功
    message.success('奖品信息已更新');
    
    setTimeout(() => {
      navigate(`/EditPrizes/${id}`);
    }, 1000);
  } catch (err) {
    console.error('更新出错：', err); // ✅ 捕获并查看错误原因
    setError('更新失败');
    message.error('更新失败，请稍后重试');
    <Button onClick={() => message.success('测试弹窗')}>测试提示</Button>

  }
};



  if (loading)
    return (
      <Spin size="large" style={{ display: 'block', margin: '100px auto' }} />
    );

  return (
    <div style={{ maxWidth: 600, margin: '40px auto' }}>
      <Card bordered={false}>
        <Title level={3} style={{ textAlign: 'center' }}>
          编辑奖品
        </Title>

        {error && (
          <Alert message={error} type="error" showIcon style={{ marginBottom: 16 }} />
        )}

        <Form layout="vertical" onFinish={handleSubmit}>
          <Form.Item label="上传奖品图片">
            <Upload
              name="file"
              action="http://localhost:5000/api/upload" // 你的上传接口
              listType="picture"
              fileList={fileList}
              onChange={handleUploadChange}
              onRemove={handleRemove}
              maxCount={1}
              accept="image/*"
              disabled={uploading}
            >
              <Button icon={<UploadOutlined />} loading={uploading}>
                点击上传
              </Button>
            </Upload>
          </Form.Item>

          <Form.Item label="奖品名称" required>
            <Input
              name="prize_name"
              value={formData.prize_name}
              onChange={handleChange}
              placeholder="请输入奖品名称"
            />
          </Form.Item>

          <Form.Item label="奖品描述" required>
            <TextArea
              name="prize_description"
              value={formData.prize_description}
              onChange={handleChange}
              rows={4}
              placeholder="请输入奖品描述"
            />
          </Form.Item>

          <Form.Item label="所需积分" required>
            <InputNumber
              name="points"
              value={formData.points}
              onChange={(value) => handleNumberChange(value, 'points')}
              min={0}
              style={{ width: '100%' }}
              placeholder="请输入所需积分"
            />
          </Form.Item>

          <Form.Item label="库存数量" required>
            <InputNumber
              name="stock"
              value={formData.stock}
              onChange={(value) => handleNumberChange(value, 'stock')}
              min={0}
              style={{ width: '100%' }}
              placeholder="请输入库存数量"
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block disabled={uploading}>
              保存修改
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default EditPrize;
